/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifrn.Dao;

import br.edu.ifrn.Classes.Area;
import br.edu.ifrn.Classes.Conexao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author MONTENEGRO
 */
public class AreaDao {

    private Connection connection;

    public AreaDao() {
        this.connection = new Conexao().getConnection();

    }

    public void InserirArea(Area area) throws SQLException {
        String sql = "insert into area" + "(id, nome, descricao)"
                + "values(?,?,?)";
        try {
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setInt(1, area.getIdArea());
            stmt.setString(2, area.getNomeArea());
            stmt.setString(3, area.getDescricaoArea());
            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void RemoverArea(Area area) {
        try {
            PreparedStatement stmt = connection.prepareStatement("delete from area where id=?");
            stmt.setInt(1, area.getIdArea());
            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public void EditarArea(Area area) {

        String sql = "update area set nome=?, descricao=? where id=?";

        try {
            PreparedStatement stmt = this.connection.prepareStatement(sql);
            stmt.setString(1, area.getNomeArea());
            stmt.setString(2, area.getDescricaoArea());
            stmt.setInt(3, area.getIdArea());

            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
    }

    public List<Area> GetLista() {

        try {
            List<Area> areas = new ArrayList<Area>();
            PreparedStatement stmt = connection.prepareStatement("select * from area");
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                //criando um objeto Area
                Area area = new Area();
                area.setIdArea(rs.getInt("id"));
                area.setNomeArea(rs.getString("nome"));
                area.setDescricaoArea(rs.getString("descricao"));

                //adicionando o objeto a uma lista
                areas.add(area);
            }
            rs.close();
            stmt.close();

            return areas;
        } catch (SQLException e) {

            throw new RuntimeException(e);
        }

    }
}
